/*!
 * jQuery placeholder plugin
 *
 * 占位符插件，支持大部分主流浏览器
 * 
 * Usage: $('.placeholderInput').placeholder({ color : '#eee' });
 * Author: rttianqingsen@huawei.com
 */
(function(jQuery, undef){ 

    jQuery.String = {
        EMPTY : '',
        toString : Object.prototype.toString,
        
        isString : function(str) {
	        return typeof(str) == 'string';
	    },
	    
        isPlainObject : function(o) { 
	        /** 
	         * note by yiminghe 
	         * isPlainObject(node=document.getElementById("xx")) -> false 
	         * toString.call(node) : ie678 == '[object Object]',other =='[object HTMLElement]' 
	         * 'isPrototypeOf' in node : ie678 === false ,other === true 
	         */
	        return o && $.String.toString.call(o) === '[object Object]' && 'isPrototypeOf' in o; 
	    },
	    
	    substitute : function(str, o, regexp) {
	        if (!(jQuery.type(str) === 'string') || !(jQuery.isPlainObject(o))) {
	            return str;
	        }
	        return str.replace(regexp || /\\?\{([^{}]+)\}/g, function(match, name) {
                if (match.charAt(0) === '\\') {
                    return match.slice(1);
                } 
                return (o[name] !== undef) ? o[name] : jQuery.String.EMPTY; 
	        }); 
	    }
    };
	
	// ----------------------------------------------------------------------------
    //-----------------------------扩展的插件方法----------------------------
    //----------------------------------------------------------------------------  
    var docloaded = false; // 确保HTML加载完毕
    jQuery(document).ready(function() {docloaded = true} );
    
    var ieVersion = jQuery.browser.msie ? parseFloat(jQuery.browser.version) : 0; // IE浏览器版本
    var isSupport = 'placeholder' in document.createElement('input'); // input是否支持placeholder
    var WRAP_TMPL = '<div class="placeholder" style="position: relative;zoom:1;display:'+(ieVersion>7?'inline-block':'inline')+';"></div>';
    var TIP_TMPL = '<label style="position:absolute;left:1px;top:1px;display:'+(ieVersion>7?'inline-block':'inline')+'">{tip}</label>'; // 提示信息
    
    /**
     * 该插件的主方法
     */
    jQuery.fn.placeholder = function(settings) {
        if (isSupport) {
            return;
        }
        return this.each(function() {
            if (!docloaded) {
                $(document).ready(function() {
                    jQuery.fn.placeholder.init(this, settings);
                });
            } else {
                jQuery.fn.placeholder.init(this, settings);
            }
        });
    };
    
    /* Default Settings */ 
    jQuery.fn.placeholder.defaults = {
        color:             false,
        fontSize:          false
    };
    jQuery.fn.placeholder.settings = {};
    
    /**
	 * 初始化占位符
	 */
	jQuery.fn.placeholder.init = function(element, settings) {
	    var self = element;
	    var target = jQuery(element);
	    if (!element) {
	        if(typeof(console) !== 'undefined' && console != null) console.log('[placeholder] has no element to decorate');
	        return;
	    }
	    
	    settings = jQuery.extend({}, jQuery.fn.placeholder.defaults, settings);
        jQuery.fn.placeholder.settings = settings;
        
        var placeHolderTip = target.attr('placeholder');
        
        if (!placeHolderTip) return;
        
        // -- 工具方法  --   
        // 获取值
        var getContent = function(el){
            return jQuery(el).val();
        };
        
        // 隐藏占位符
        var hidePlaceholder = function(el) {
            self.triggerLabel.hide();
        };
        
        // 显示占位符
        var showPlaceholder = function(el) {
            self.triggerLabel.show();
        };
        
        // 内容是否为空
        var isContentEmpty = function(el){
            var content = getContent(el);
            return content.length === 0;
        };
        
        // 设置占位符样式
        var setPlaceholderStyle = function($o) {
            var placeWidth = target.width() + 4;
            var placeHeight = target.height() + 4;
            $o.width(placeWidth).height(placeHeight).css('line-height',placeHeight+'px');
            if (settings.color) {
                $o.css('color', settings.color);
            }
            if (settings.fontSize) {
                $o.css('font-size',settings.fontSize);
            }
            // 鼠标移上去变成文本光标
            $o.css('cursor', 'text');
        };
        
        // 包装占位符
        function _decorate() {
            // 创建一个label
            var str = jQuery.String.substitute(TIP_TMPL, { tip:placeHolderTip });
            var triggerLabel = self.triggerLabel = jQuery(str);
            setPlaceholderStyle(triggerLabel);
            if(target.attr('id')) {
                triggerLabel.attr('for', target.attr('id'));
            } else {
                triggerLabel.bind('click', function(jQuery) {
                    target[0].focus();
                });
            }
            
            // create parent 
            var targetBox = jQuery(WRAP_TMPL);
            target.wrap(targetBox);
            
            // insertbefore target
            triggerLabel.insertBefore(target);
            
            if (!isContentEmpty(element)) {
                triggerLabel.hide();
            }
            
            if(typeof(console) !== 'undefined' && console != null) {
                console.log(target.attr('name') + ' placeholder');
            }
        };
        
        // ----- 事件处理 -----
        target.bind('focus', function(ev) {
            hidePlaceholder();
        });

        target.bind('blur', function(ev) {
            if(!target.val()) {
                showPlaceholder();
            }
        });
        
        // ----- 执行 -----
        _decorate();
        
	};
    
})(jQuery);
